﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.ComponentModel;

namespace AmazedSaint.Vingy.ViewModels
{

    /// <summary>
    /// A minimal async delegate command implementation
    /// </summary>
    public class AsyncDelegateCommand : ICommand
    {

        BackgroundWorker worker = new BackgroundWorker();
        bool canExecute = true;

        public AsyncDelegateCommand(Action action, 
            Action<RunWorkerCompletedEventArgs> completed=null)
        {

            worker.DoWork += (s, e) =>
                {
                    canExecute = false;
                    action();
                };

            worker.RunWorkerCompleted += (s, e) =>
            {
                if (completed != null) completed(e);
                canExecute = true;
            };
        }

        public bool CanExecute(object parameter)
        {
            return canExecute;
        }

        public event EventHandler CanExecuteChanged = delegate { };

        public void Execute(object parameter)
        {
            worker.RunWorkerAsync();
        }
    }
}
